package com.xiaoyu.lanling.feature.mine

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.app.GlobalUI
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.feature.main.controller.MainActivityViewController
import com.xiaoyu.lanling.feature.mine.controller.MainMineViewController
import com.xiaoyu.lanling.feature.view.StatusLayout
import com.xiaoyu.lanling.view.OnShowFragment

class MainMineFragment : OnShowFragment() {

    private lateinit var mRootView: StatusLayout
    private var mView: View? = null

    private var mController: MainMineViewController? = null
    private var isInitIndex = false

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mRootView = StatusLayout(AppContext.getContext())
        mRootView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        return mRootView
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        super.onViewCreatedSafelyAfterAppFinishInit(view, savedInstanceState)
        arguments?.let {
            val initIndex = it.getInt(Constant.PARAM_INDEX, -1)
            isInitIndex = initIndex == MainActivityViewController.MAIN_VIEW_PAGER_MINE
            if (isInitIndex) {
                tryToInitViewAndController()
            }
        }
    }

    override fun onStartSafelyAfterAppFinishInit(isFirstTimeStart: Boolean) {
        super.onStartSafelyAfterAppFinishInit(isFirstTimeStart)
        if (isFirstTimeStart) {
            return
        }
        mController?.onStart(isFirstTimeStart)
    }

    override fun onShowSafelyAfterAppFinishInit() {
        super.onShowSafelyAfterAppFinishInit()
        if (!isInitIndex) {
            tryToInitViewAndController()
        }
    }

    private fun tryToInitViewAndController() {
        if (activity == null) {
            GlobalUI.getInstance().showToast(R.string.main_root_fragment_error)
            return
        }
        if (mView == null) {
            mView = mRootView.showLazyViewWithLoading(LayoutInflater.from(activity), R.layout.fragment_main_mine)
        }
        if (mController == null) {
            mController = MainMineViewController(this)
            mController?.onStart(true)
        }
    }
}